public class offer55_2 {
    public boolean isBalanced(TreeNode root) {
        if(root == null) {
            return true;
        }
        int left = dfs(root.left);
        int right = dfs(root.right);
        return Math.abs(left - right) <= 1 && isBalanced(root.left) && isBalanced(root.right);
    }

    private int dfs(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int left = dfs(root.left);
        int right = dfs(root.right);
        return 1 + Math.max(left,right);
    }
}
